
#include "BallView.h"
#include "TitleView.h"
#include "Application.h"

//
// Constructor
//

BallView::BallView()
: speed(90.0f), 
	friction(0.98f)
{
	// Initialize variables
	x=100.0f, y=100.0f;
	dx=0.0f, dy=0.0f;

	// Load in the sound
	snd = hge->Effect_Load("data/menu.wav");
	particle.tex = hge->Texture_Load("data/particles.png");

	// Setup the bgQuad
	particle.blend = BLEND_ALPHABLEND | BLEND_COLORMUL | BLEND_NOZWRITE;
	
	for(int i=0; i < 4; i++)
	{
		// Set up z-coordinate of vertices
		particle.v[i].z = 0.5f;
		// Set up color. The format of DWORD col is 0xAARRGGBB
		particle.v[i].col = 0xFFFFA000;
	}

	// Sets the texture coordinates
	particle.v[0].tx=96.0/128.0; particle.v[0].ty=64.0/128.0; 
	particle.v[1].tx=128.0/128.0; particle.v[1].ty=64.0/128.0; 
	particle.v[2].tx=128.0/128.0; particle.v[2].ty=96.0/128.0; 
	particle.v[3].tx=96.0/128.0; particle.v[3].ty=96.0/128.0; 
}

//
// Destructor
//

BallView::~BallView()
{
	hge->Effect_Free(snd);
	hge->Texture_Free(particle.tex);
}

//
// Process
//

View *BallView::Process()
{
	// Get the time elapsed since last call of FrameFunc().
	// This will help us to synchronize on different
	// machines and video modes.
	float dt = hge->Timer_GetDelta();

	// Process keys
	if (hge->Input_GetKeyState(HGEK_ESCAPE)) return GetTitleView();
	if (hge->Input_GetKeyState(HGEK_LEFT)) dx-=speed*dt;
	if (hge->Input_GetKeyState(HGEK_RIGHT)) dx+=speed*dt;
	if (hge->Input_GetKeyState(HGEK_UP)) dy-=speed*dt;
	if (hge->Input_GetKeyState(HGEK_DOWN)) dy+=speed*dt;

	// Do some movement calculations and collision detection	
	dx*=friction; dy*=friction; x+=dx; y+=dy;
	if(x>784) {x=784-(x-784);dx=-dx;boom();}
	if(x<16) {x=16+16-x;dx=-dx;boom();}
	if(y>584) {y=584-(y-584);dy=-dy;boom();}
	if(y<16) {y=16+16-y;dy=-dy;boom();}

	// Set up quad's screen coordinates
	particle.v[0].x=x-16; particle.v[0].y=y-16;
	particle.v[1].x=x+16; particle.v[1].y=y-16;
	particle.v[2].x=x+16; particle.v[2].y=y+16;
	particle.v[3].x=x-16; particle.v[3].y=y+16;

	return this;
}

//
// Render
//

void BallView::Render()
{
	// Clear screen with black color
	hge->Gfx_Clear(0);

	// Render quads here. This time just
	// one of them will serve our needs.
	hge->Gfx_RenderQuad(&particle);
}

//
// Boom
//

void BallView::boom() 
{
	int pan=int((x-400)/4);
	float pitch=(dx*dx+dy*dy)*0.0005f+0.2f;
	hge->Effect_PlayEx(snd,100,pan,pitch);
}